package com.xiaoming.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaoming.User;
import com.xiaoming.UserService;
import com.xiaoming.utils.RpcRequest;
import com.xiaoming.utils.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import com.xiaoming.SpringContextUtils;
import com.xiaoming.service.UserServiceImpl;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        try {
            RpcRequest rpcRequest =(RpcRequest)msg;
            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Object[] parameters = rpcRequest.getParameters();
            Class<?>[] parameterTypes = rpcRequest.getParameterTypes();

            Class<?> aClass = Class.forName(className);

            UserService o = (UserServiceImpl) SpringContextUtils.getBean(aClass);
            Method method = aClass.getMethod(methodName, parameterTypes);
            method.setAccessible(true);
            parameters[0] =JSON.toJavaObject((JSONObject) parameters[0],User.class);
            //反射调用
            Object result = method.invoke(o, parameters);

            //返回客户端响应信息
            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setData(result);
            rpcResponse.setClientName("服务端1");
            rpcResponse.setCode("OK");
            rpcResponse.setMessage("请求成功");
            ctx.writeAndFlush(rpcResponse);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
